"""
通用函数集
"""
import requests
from os import path, mkdir
from requests.exceptions import *
from urllib3.exceptions import *


def _writer(dir, file_name, file):
    """
    mkdir
    :param dir:
    :param file:
    :return:
    """
    _dir = ''
    for i in dir.split('/'):
        _dir = _dir + i + '/'
        if not path.exists(_dir): mkdir(_dir)
    with open(f"{dir}/{file_name}", mode='w', encoding='utf8')as f:
        f.write(f"{file}")
    return 'ok'


def getHtml(url):
    """ get a code from a html through url.
     :return A str about the html.
     """
    global page
    headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
    try:
        page = requests.get(url, headers=headers)
        page.encoding = "gb2312"
        if page.status_code is 200:
            page = page.text
        else:
            print("网页获取获取错误。")
            return 'Error'
    except ConnectionError:
        print("连接错误")
        return 'Error'
    except TimeoutError:
        print("连接超时")
        return 'Error'
    _writer('./Support', f'{url[-7:]}', page)
    return page
# 获取任意一个网页的源代码，以字符串的形式返回。
# This function can get a source code of discretionary html, then return a string.
